package com.leoman.service.impl;

import com.leoman.controller.common.CommonController;
import com.leoman.core.Constant;
import com.leoman.dao.*;
import com.leoman.entity.*;
import com.leoman.exception.MoneyShortException;
import com.leoman.exception.NoDataException;
import com.leoman.exception.ParamErrorException;
import com.leoman.service.MindService;
import com.leoman.utils.DateUtils;
import com.leoman.utils.JsonUtil;
import com.leoman.utils.QiNiuUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * MindServiceImpl
 * Created by 涂奕恒 on 2016/11/23 0023 下午 4:00.
 */
@Service
public class MindServiceImpl implements MindService {

    @Autowired
    private MindDao mindDao;

    @Autowired
    private PraiseDao praiseDao;

    @Autowired
    private CommentDao commentDao;

    @Autowired
    private UserCollectDao userCollectDao;

    @Autowired
    private UserLetterMindDao userLetterMindDao;

    @Autowired
    private ImageDao imageDao;

    @Autowired
    private UserDao userDao;

    @Override
    public List<Mind> findAll() {
        return mindDao.findAll();
    }

    @Override
    public Page<Mind> find(int pageNum, int pageSize) {
        return mindDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<Mind> find(int pageNum) {
        return find(pageNum, Constant.PAGE_DEF_SIZE);
    }

    @Override
    public Mind getById(int id) {
        return mindDao.findOne(id);
    }

    @Override
    @Transactional
    public void deleteById(int id) {
        List<String> tempUrl = new ArrayList<>();
        List<Image> imageList;
        Mind mind = mindDao.findOne(id);

        // 删除该心事的所有评论
        List<Comment> commentList = commentDao.findListBySourceIdAndType(id, Constant.SOURCE_TYPE_MIND);
        for (Comment comment : commentList) {
            // 删除评论中的图片
            System.out.println();
            imageList = imageDao.findListByParams(comment.getId(), Constant.SOURCE_TYPE_COMMENT);
            for (Image image : imageList) {
                tempUrl.add(image.getUrl());
                imageDao.delete(image);
            }
            System.out.println();
            // 删除评论中的语音文件
            if (comment.getVoiceTime() > 0) {
                tempUrl.add(comment.getContent());
            }

            commentDao.delete(comment.getId());
        }

        // 删除该心事的所有收藏
        List<UserCollect> collectList = userCollectDao.findListBySourceIdAndType(id, Constant.SOURCE_TYPE_MIND);
        for (UserCollect userCollect : collectList) {
            userCollectDao.delete(userCollect);
        }

        // 删除该心事的所有点赞
        List<Praise> praiseList = praiseDao.findListBySourceIdAndType(id, Constant.SOURCE_TYPE_MIND);
        for (Praise praise : praiseList) {
            praiseDao.delete(praise);
        }

        // 删除该心事的所有图片
        imageList = imageDao.findListByParams(id, Constant.SOURCE_TYPE_MIND);
        for (Image image : imageList) {
            tempUrl.add(image.getUrl());
            imageDao.delete(image);
        }

        tempUrl.add(mind.getCover());

        mindDao.delete(id);

        for (String url : tempUrl) {
            QiNiuUtils.delete(url);
        }
    }

    @Override
    public Mind create(Mind mind) {
        return mindDao.save(mind);
    }

    @Override
    public Mind update(Mind mind) {
        return mindDao.save(mind);
    }

    @Override
    @Transactional
    public void deleteAll(int[] ids) {
        for (int id : ids) {
            deleteById(id);
        }
    }

    @Override
    public Page<Mind> iPageForApp(final Integer userId, final Integer isMe, Integer pageNum, Integer pageSize) {
        Integer[] info = CommonController.getPageParams(pageNum, pageSize);

        Page<Mind> page = mindDao.findAll(new Specification<Mind>() {
            @SuppressWarnings("ToArrayCallWithZeroLengthArrayArgument")
            @Override
            public Predicate toPredicate(Root<Mind> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate result = null;
                List<Predicate> predicateList = new ArrayList<>();

                if (null != userId && null != isMe && isMe.equals(Constant.USER_STATUS_YES)) {
                    predicateList.add(cb.equal(root.get("user").get("id").as(Integer.class), userId));
                } else {
                    predicateList.add(cb.equal(root.get("isDraft").as(Integer.class), Constant.USER_STATUS_NO));
                }

                if (predicateList.size() > 0) {
                    result = cb.and(predicateList.toArray(new Predicate[]{}));
                }

                if (result != null) {
                    query.where(result);
                }
                return query.getGroupRestriction();
            }

        }, new PageRequest(info[0] - 1, info[1], Sort.Direction.DESC, "isAdmin", "isTop", "id"));

        for (Mind mind : page.getContent()) {
            changeMindInfo(mind, null == isMe || isMe.equals(Constant.USER_STATUS_NO) ? userId : null);
        }

        return page;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Page<Mind> iPageForAppCollect(Integer userId, Integer pageNum, Integer pageSize) {
        Integer[] info = CommonController.getPageParams(pageNum, pageSize);
        PageRequest pageRequest = new PageRequest(info[0] - 1, info[1], Sort.Direction.DESC, "id");

        final Page<UserCollect> userCollectPage = userCollectDao.iPageByUserId(userId, Constant.SOURCE_TYPE_MIND, pageRequest);

        List<Mind> list = new ArrayList<>();

        for (UserCollect userCollect : userCollectPage.getContent()) {
            list.add(mindDao.findOne(userCollect.getSourceId()));
        }

        Page<Mind> mindPage = new PageImpl(list, pageRequest, userCollectPage.getTotalElements());

        for (Mind mind : mindPage.getContent()) {
            changeMindInfo(mind, userId);
        }

        return mindPage;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Page<Mind> iPageForAppOpen(Integer userId, Integer pageNum, Integer pageSize) {
        Integer[] info = CommonController.getPageParams(pageNum, pageSize);
        PageRequest pageRequest = new PageRequest(info[0] - 1, info[1], Sort.Direction.DESC, "id");

        final Page<UserLetterMind> userLetterMindPage = userLetterMindDao.iPageByParamsPlus(userId, pageRequest);

        List<Mind> list = new ArrayList<>();

        for (UserLetterMind userLetterMind : userLetterMindPage.getContent()) {
            list.add(mindDao.findOne(userLetterMind.getSourceId()));
        }

        Page<Mind> mindPage = new PageImpl(list, pageRequest, userLetterMindPage.getTotalElements());

        for (Mind mind : mindPage.getContent()) {
            changeMindInfo(mind, userId);
        }

        return mindPage;
    }

    @Override
    public Mind iFindOneForApp(Integer mindId, Integer userId) throws ParamErrorException, NoDataException {
        if (null == mindId) {
            throw new ParamErrorException();
        }

        Mind mind = mindDao.findOne(mindId);

        if (null == mind) {
            throw new NoDataException();
        }

        changeMindInfo(mind, null == mind.getUser() || mind.getUser().getId().equals(userId) ? null : userId);

        mind.setImageList(imageDao.findListByParams(mindId, Constant.SOURCE_TYPE_MIND));

        return mind;
    }

    @Override
    @Transactional
    public void addMindInfo(Boolean isAdmin,
                            Integer tempId,
                            Integer userId,
                            String title,
                            String content,
                            String openMoney,
                            Integer imgNum,
                            Integer isDraft,
                            MultipartRequest multipartRequest) throws ParamErrorException {
        if (null == userId || StringUtils.isBlank(title) || StringUtils.isBlank(content) || null == isDraft) {
            throw new ParamErrorException();
        }

        Mind mind;

        if (null == tempId) {
            mind = new Mind();
        } else {
            mind = mindDao.findOne(tempId);
        }

        MultipartFile cover = multipartRequest.getFile("cover");

        User user = new User();
        user.setId(userId);

        mind.setUser(user);
        mind.setTitle(title);

        if (null != cover && cover.getSize() > 0) {
            QiNiuUtils.delete(mind.getCover());
            mind.setCover(QiNiuUtils.upload(cover));
        }

        if (content.length() > 40) {
            mind.setSynopsis(content.substring(0, 40));
        } else {
            mind.setSynopsis(content);
        }
        mind.setContent(content);

        if (StringUtils.isNotBlank(openMoney)) {
            mind.setOpenMoney(Double.parseDouble(openMoney));
        }

        mind.setIsAdmin(isAdmin ? Constant.USER_STATUS_YES : Constant.USER_STATUS_NO);
        mind.setIsDraft(isDraft);

        if (isDraft.equals(Constant.USER_STATUS_YES)) {
            Mind tempMind = mindDao.iFindDraftByUserId(userId);
            deleteById(tempMind.getId());
        }

        mindDao.save(mind);

        if (null != tempId) {
            List<Image> imageList = imageDao.findListByParams(tempId, Constant.SOURCE_TYPE_MIND);

            for (Image image : imageList) {
                QiNiuUtils.delete(image.getUrl());

                imageDao.delete(image.getId());
            }
        }

        // 保存心事图片信息
        List<MultipartFile> list = multipartRequest.getFiles("image");

        Image image;
        for (MultipartFile file : list) {
            if (null != file && file.getSize() > 0) {
                image = new Image();
                image.setUrl(QiNiuUtils.upload(file));
                image.setSourceId(mind.getId());
                image.setSourceType(Constant.SOURCE_TYPE_MIND);

                imageDao.save(image);
            }
        }
    }

    @Override
    public Integer getMindInfo(Integer userId, Integer mindId) throws ParamErrorException {
        if (null == userId || null == mindId) {
            throw new ParamErrorException();
        }

        User user = new User();
        user.setId(userId);

        UserLetterMind userLetterMind = userLetterMindDao.findOneByParams(userId, mindId, 2);
        if (null == userLetterMind) {
            userLetterMind = new UserLetterMind();

            userLetterMind.setUser(user);
            userLetterMind.setSourceId(mindId);
            userLetterMind.setSourceType(2);

            userLetterMindDao.save(userLetterMind);
        }

        return userLetterMind.getId();
    }

    @Override
    public Mind iFindDraftByUserId(Integer userId) throws ParamErrorException, NoDataException {
        return mindDao.iFindDraftByUserId(userId);
    }

    @Override
    public Page<Mind> pageByParams(final String title, final String userName, final String startTime, final String endTime, Integer pageNum, Integer pageSize) {
        return mindDao.findAll(new Specification<Mind>() {
            @SuppressWarnings("ToArrayCallWithZeroLengthArrayArgument")
            @Override
            public Predicate toPredicate(Root<Mind> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate result = null;
                List<Predicate> predicateList = new ArrayList<>();

                if (StringUtils.isNotBlank(title)) {
                    predicateList.add(cb.like(root.get("title").as(String.class), "%" + title + "%"));
                }

                if (StringUtils.isNotBlank(userName)) {
                    predicateList.add(cb.like(root.get("user").get("nickName").as(String.class), "%" + userName + "%"));
                }

                if (StringUtils.isNotBlank(startTime)) {
                    try {
                        System.out.println("._");
                        Long startDate = DateUtils.stringToDateWithFormat(startTime, "yyyy-MM-dd hh:mm:ss").getTime();
                        predicateList.add(cb.gt(root.get("createTime").as(Long.class), startDate));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

                if (StringUtils.isNotBlank(endTime)) {
                    try {
                        System.out.println("._");
                        Long endDate = DateUtils.stringToDateWithFormat(endTime, "yyyy-MM-dd hh:mm:ss").getTime();
                        predicateList.add(cb.lt(root.get("createTime").as(Long.class), endDate));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

                predicateList.add(cb.equal(root.get("isDraft").as(Integer.class), Constant.USER_STATUS_NO));

                if (predicateList.size() > 0) {
                    result = cb.and(predicateList.toArray(new Predicate[]{}));
                }

                if (result != null) {
                    query.where(result);
                }
                return query.getGroupRestriction();
            }

        }, new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "isAdmin", "isTop", "id"));
    }

    @Override
    public Integer toTop(Integer mindId) {
        try {
            Mind topMind = mindDao.iFindOneWithTop();
            Mind mind = mindDao.findOne(mindId);

            if (null != topMind && mindId.equals(topMind.getId())) {
                return -1;
            }

            if (null != topMind) {
                topMind.setIsTop(Constant.USER_STATUS_NO);
                mindDao.save(topMind);
            }

            mind.setIsTop(Constant.USER_STATUS_YES);
            mindDao.save(mind);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Integer batchDelete(String ids) {
        try {
            Integer[] mindIds = JsonUtil.json2Obj(ids, Integer[].class);
            System.out.println();
            for (Integer mindId : mindIds) {
                deleteById(mindId);
            }

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    @Transactional
    public Integer saveMind(String title, String txtVal, String content, String openMoney, MultipartRequest multipartRequest) {
        try {
            MultipartFile cover = multipartRequest.getFile("cover");
            Mind mindByAdmin = mindDao.iFindOneWithAdmin();

            if (null != mindByAdmin) {
                deleteById(mindByAdmin.getId());
            }

            mindByAdmin = new Mind();
            mindByAdmin.setTitle(title);
            if (txtVal.length() > 40) {
                mindByAdmin.setSynopsis(txtVal.substring(0, 40));
            } else {
                mindByAdmin.setSynopsis(txtVal);
            }
            mindByAdmin.setContent(content);
            mindByAdmin.setOpenMoney(Double.parseDouble(openMoney));
            if (null != cover && cover.getSize() > 0) {
                mindByAdmin.setCover(QiNiuUtils.upload(cover));
            }
            mindByAdmin.setIsAdmin(Constant.USER_STATUS_YES);

            mindDao.save(mindByAdmin);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public void changeMoneyStatus(Integer id) {
        UserLetterMind userLetterMind = userLetterMindDao.findOne(id);

        if (null != userLetterMind && userLetterMind.getMoneyStatus().equals(Constant.USER_STATUS_NO)) {
            userLetterMind.setMoneyStatus(Constant.USER_STATUS_YES);

            userLetterMindDao.save(userLetterMind);
        }
    }

    @Override
    public void changeMoneyStatusByMoney(Integer sourceId, Double money) throws ParamErrorException, MoneyShortException {
        UserLetterMind userLetterMind = userLetterMindDao.findOne(sourceId);

        User user;

        if (null != userLetterMind) {
            // 修改用户账户余额
            user = userLetterMind.getUser();

            if (null == user) {
                throw new ParamErrorException();
            }

            if (user.getMoney() < money) {
                throw new MoneyShortException();
            }

            user.setMoney(user.getMoney() - money);
            userDao.save(user);

            userLetterMind.setMoneyStatus(Constant.USER_STATUS_YES);
            userLetterMindDao.save(userLetterMind);
        } else {
            throw new ParamErrorException();
        }
    }

    /**
     * 加载心事附属信息
     *
     * @param mind   心事信息
     * @param userId 用户ID
     */
    private void changeMindInfo(Mind mind, Integer userId) {
        UserLetterMind userLetterMind;

        if (null == userId) {
            mind.setIsPraise(Constant.USER_STATUS_NO);
            mind.setIsCollect(Constant.USER_STATUS_NO);
            mind.setIsGet(Constant.USER_STATUS_NO);
        } else {
            mind.setIsPraise(null == praiseDao.findOneByParams(userId, mind.getId(), Constant.SOURCE_TYPE_MIND) ? Constant.USER_STATUS_NO : Constant.USER_STATUS_YES);
            mind.setIsCollect(null == userCollectDao.findOneByParams(userId, mind.getId(), Constant.SOURCE_TYPE_MIND) ? Constant.USER_STATUS_NO : Constant.USER_STATUS_YES);
            userLetterMind = userLetterMindDao.findOneByParams(userId, mind.getId(), 2);
            mind.setIsGet(null == userLetterMind || userLetterMind.getMoneyStatus().equals(Constant.USER_STATUS_NO) ? Constant.USER_STATUS_NO : Constant.USER_STATUS_YES);
        }

        Integer praiseNum = praiseDao.findListBySourceIdAndType(mind.getId(), Constant.SOURCE_TYPE_MIND).size();
        Integer commentNum = commentDao.findListBySourceIdAndType(mind.getId(), Constant.SOURCE_TYPE_MIND).size();

        mind.setPraiseNum(praiseNum * 2 + commentNum);
        mind.setCommentNum(commentNum);
        mind.setCollectNum(userCollectDao.findListBySourceIdAndType(mind.getId(), Constant.SOURCE_TYPE_MIND).size());
        mind.setContent(mind.getContent().replaceAll("&lt", "<").replaceAll("&gt", ">"));

        if (mind.getIsAdmin().equals(Constant.USER_STATUS_NO)) {
            // 不是管理员
            mind.setUserId(mind.getUser().getId());
            mind.setAvatar(mind.getUser().getAvatar());
            mind.setNickName(mind.getUser().getNickName());
            mind.setRegionId(null != mind.getUser().getRegion() ? mind.getUser().getRegion().getId() : null);
            mind.setRegionInfo(null != mind.getUser().getRegion() ? mind.getUser().getRegion().getCity().getProvince().getName() + "|" + mind.getUser().getRegion().getCity().getName() : "");
        }
    }
}